package com.gitee.ed.arithmetic.leetcode.answer.answer_1_100.answer_1_10;

import com.gitee.ed.arithmetic.leetcode.solution.solution_1_100.solution_1_10.Solution8;

/**
 * @author hongda.li
 */
public class Answer8 implements Solution8 {
    @Override
    public int myAtoi(String s) {
        char[] c = s.trim().toCharArray();

        if (c.length == 0) {
            return 0;
        }

        int res = 0;

        int max = Integer.MAX_VALUE / 10;

        int start = 1;
        boolean posttive = true;

        // 设置符号位
        if (c[0] == '-') {
            posttive = false;
        }
        // 从首位开始判断，如果开头为+号，则从一号位开始判断
        else if (c[0] != '+') {
            start = 0;
        }

        for (int j = start; j < c.length; j++) {
            // 非数字跳过
            if (c[j] < '0' || c[j] > '9') {
                break;
            }

            // 超过最大值
            if (res > max || res == max && c[j] > '7') {
                return posttive ? Integer.MAX_VALUE : Integer.MIN_VALUE;
            }

            res = res * 10 + (c[j] - '0');
        }

        return posttive ? res : -res;
    }
}
